package com.shjn.squirrel.fragment;

import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.text.style.ImageSpan;
import android.text.style.RelativeSizeSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.shjn.squirrel.R;
import com.shjn.squirrel.adapter.GenerateAdapter;
import com.shjn.squirrel.application.MyApplication;
import com.shjn.squirrel.bean.otherBean.UserDeliverRecord;
import com.shjn.squirrel.bean.storageBean.WastePrice;
import com.shjn.squirrel.customView.BackAndTimerView;
import com.shjn.squirrel.model.Constant;
import com.shjn.squirrel.model.LocalStorage;
import com.shjn.squirrel.model.UserInfoCache;
import com.shjn.squirrel.utils.SoundPlayUtils;

import java.util.ArrayList;

/**
 * 用户投递多于三种垃圾的显示记录
 */
public class UserRecordMoreFragment extends BaseFragment implements View.OnClickListener {

    private static UserRecordMoreFragment instance;
    private ListView mUserRecord;
    private GenerateAdapter<UserDeliverRecord> mDeliverRecordAdapter;
    private Button mBtnOVer;
    private Button mBtnAgain;
    private TextView mTvMoney;
    private TextView mTvEncourage;
    private ArrayList<WastePrice> mWastePrice;

    public UserRecordMoreFragment() {
    }

    public synchronized static UserRecordMoreFragment getInstance() {
        if (instance == null) {
            instance = new UserRecordMoreFragment();
        }
        return instance;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return createView(inflater, R.layout.user_deliver_record_more, container);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initTimer();
        initView();
    }

    /**
     * 初始化倒计时器
     */
    private void initTimer() {
        //加载定时器面板，设置定时时间
        mActivity.mBackAndTimer.setOnBackListener(null).setBackVisibleState(false)
                .setOnTimerFinishListener(new BackAndTimerView.OnTimerFinishListener() {
                    @Override
                    public void onTimerFinish() {
                        //跳转到结束投递页
                        if (!UserFinishFragment.getInstance().isAdded()) {
                            mActivity.mBackAndTimer.stop();
                            SoundPlayUtils.play(16);//感谢使用提示音
                            mActivity.getFragmentManager().beginTransaction()
                                    .replace(R.id.mid, UserFinishFragment.getInstance())
                                    .commit();
                        }
                    }
                }).setTime(60).setVisibleState(true).start();
    }

    /**
     * 初始化相关控件
     */
    private void initView() {
        mUserRecord = (ListView) mView.findViewById(R.id.lv);
        mUserRecord.addFooterView(View.inflate(mActivity, R.layout.list_divider, null));
        initAdapter();
        mBtnOVer = (Button) mView.findViewById(R.id.btn_over);
        mBtnAgain = (Button) mView.findViewById(R.id.btn_again);
        mBtnOVer.setOnClickListener(this);
        mBtnAgain.setOnClickListener(this);
        mTvMoney = (TextView) mView.findViewById(R.id.tv_money_value);
        mTvEncourage = (TextView) mView.findViewById(R.id.tv_encourage_value);
        setSpanStr("环保金", mTvMoney);
        setSpanStr("积分", mTvEncourage);
    }

    /**
     * 设置富文本
     */
    private void setSpanStr(String str, TextView textView) {
        SpannableString spannableString = new SpannableString(
                (str.equals("环保金") ? String.format("%.2f", UserInfoCache.getTotalMoney()) : String.format("%.0f", UserInfoCache.getTotalIntegral())) + " " + str);
        spannableString.setSpan(new RelativeSizeSpan((float) (7 / 11.0)), spannableString.toString().indexOf(" ") + 1,
                spannableString.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#999999")), spannableString.toString().indexOf(" ") + 1,
                spannableString.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        textView.setText(spannableString);
    }

    /**
     * 初始化listView适配器
     */
    private void initAdapter() {

        ArrayList<UserDeliverRecord> userDeliverRecords = new ArrayList<UserDeliverRecord>();

        initAdapterData(userDeliverRecords);

        mDeliverRecordAdapter = new GenerateAdapter<UserDeliverRecord>(mActivity,
                R.layout.deliver_list_item, userDeliverRecords, new GenerateAdapter.OnInitView() {
            @Override
            public void initView(View view, Object item) {
                UserDeliverRecord realItem = (UserDeliverRecord) item;
                ImageView icon = (ImageView) view.findViewById(R.id.img_garbage_icon);
                TextView name = (TextView) view.findViewById(R.id.tv_garbage__name);
                TextView quantity = (TextView) view.findViewById(R.id.tv_garbage_quantity);
                TextView value = (TextView) view.findViewById(R.id.tv_garbage_value);
                icon.setImageResource(realItem.getIcon());
                name.setText(realItem.getName());
                quantity.setText(realItem.getQuantity());
                value.setText(realItem.getValue());
            }
        });

        mUserRecord.setAdapter(mDeliverRecordAdapter);
    }

    /**
     * 初始化适配器数据
     *
     * @param userDeliverRecords 适配器bean对象
     */
    private void initAdapterData(ArrayList<UserDeliverRecord> userDeliverRecords) {
        mWastePrice = LocalStorage.getWastePrice(MyApplication.getInstance());

        for (String key : UserInfoCache.records.keySet()) {
            if (key.equals(Constant.bottle)) {
                userDeliverRecords.add(new UserDeliverRecord(Constant.categoryMap.get(key)[2],
                        new SpannableString(key)
                        , new SpannableString(String.format("%.0f", UserInfoCache.records.get(key).get(1)) + " " + Constant.quantity_unit),
                        new SpannableString(String.format("%.2f", UserInfoCache.records.get(key).get(1) * mWastePrice.get(Constant.categoryMap.get(key)[3] - 1).getUserPrice()))));

            } else if (key.equals(Constant.glass) || key.equals(Constant.harm)) {
                SpannableString spannableString = new SpannableString(key + " 图片");
                Drawable drawable = getResources().getDrawable(R.drawable.public_flag, null);
                drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
                spannableString.setSpan(new ImageSpan(drawable), spannableString.toString().indexOf(" ") + 1, spannableString.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                userDeliverRecords.add(new UserDeliverRecord(Constant.categoryMap.get(key)[2], spannableString
                        , new SpannableString(String.format("%.0f", UserInfoCache.records.get(key).get(1)) + " " + Constant.count_unit),
                        new SpannableString(String.format("%.0f", UserInfoCache.records.get(key).get(1) * mWastePrice.get(Constant.categoryMap.get(key)[3] - 1).getUserPrice()))));

            } else {
                userDeliverRecords.add(new UserDeliverRecord(Constant.categoryMap.get(key)[2],
                        new SpannableString(key)
                        , new SpannableString(String.format("%.2f", UserInfoCache.records.get(key).get(0)) + " " + Constant.weight_unit),
                        new SpannableString(String.format("%.2f", UserInfoCache.records.get(key).get(0) * mWastePrice.get(Constant.categoryMap.get(key)[3] - 1).getUserPrice()))));

            }
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            //结束投递
            case R.id.btn_over:
                //跳转到结束投递页
                if (!UserFinishFragment.getInstance().isAdded()) {
                    mActivity.mBackAndTimer.stop();
                    SoundPlayUtils.play(16);//感谢使用提示音
                    mActivity.getFragmentManager().beginTransaction()
                            .replace(R.id.mid, UserFinishFragment.getInstance())
                            .commit();
                }
                break;
            //继续投递
            case R.id.btn_again:
                //回到首页
                if (!UserSelectFragment.getInstance().isAdded()) {
                    mActivity.mBackAndTimer.stop();
                    SoundPlayUtils.play(15);//选择垃圾类型提示音
                    mActivity.mBackAndTimer.setVisibleState(false);
                    mActivity.getFragmentManager().beginTransaction()
                            .replace(R.id.mid, UserSelectFragment.getInstance())
                            .commit();
                }
                break;
            default:
                break;
        }
    }

}
